package com.tiankong.product.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tiankong.product.entity.Attr;
import com.tiankong.product.entity.AttrAttrgroup;
import com.tiankong.product.enums.Type;
import com.tiankong.product.service.AttrAttrgroupService;
import com.tiankong.product.service.AttrService;
import net.youdi.common.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * <p>
 * 属性&属性分组关联 前端控制器
 * </p>
 *
 * @author scl
 * @since 2021-03-22
 */
@RestController
public class AttrAttrgroupRelationController {

    @Autowired
    private AttrAttrgroupService attrAttrgroupService;
    @Autowired
    private AttrService attrService;

    @GetMapping("attrgroup/{attrgroupId}/attr/relation")
    public Result attrRelation(@PathVariable("attrgroupId") Long attrgroupId){
        List<Attr> attrs =  attrAttrgroupService.getRelationAttr(attrgroupId);
        return Result.ok(attrs);
    }

    /**
     * 属性分组没有关联的属性列表
     * @param attrgroupId
     * @return
     */
    @GetMapping("attrgroup/{attrgroupId}/noattr/relation")
    public Result noaAtrRelation(@PathVariable("attrgroupId") Long attrgroupId,
            @RequestParam(value = "key",required = false) String key,
            @RequestParam(value = "pageIndex",required = false,defaultValue = "1") Integer pageIndex,
            @RequestParam(value = "pageSize",required = false,defaultValue = "10") Integer pageSize){
        Set<Long> attrIds =  attrAttrgroupService.getRelationAttrIds(attrgroupId);
        QueryChainWrapper<Attr> query = attrService.query().eq("attr_type", Type.Attr.BASE.getCode());
        if (CollectionUtil.isNotEmpty(attrIds)){
            query.notIn("attr_id",attrIds);
        }
        if (StringUtils.hasText(key)){
            query.like("attr_name",key);
        }
        Page<Attr> page = query.page(new Page<>(pageIndex, pageSize));
        return Result.ok().setPage(page.getTotal(),page.getRecords());
    }
    /**
     * 属性分组与属性关联
     * @param relations
     * @return
     */
    @PostMapping("attrgroup/attr/relation")
    public Result noaAtrRelation(@RequestBody List<AttrAttrgroup> relations){
        attrAttrgroupService.saveBatch(relations);
        return Result.ok();
    }
    @DeleteMapping("attrgroup/attr/relation/delete")
    public Result noaAtrRelation(@RequestBody AttrAttrgroup relation){
        attrAttrgroupService.update().eq("attr_group_id",relation.getAttrGroupId()).in("attr_id",relation.getAttrIds()).remove();
        return Result.ok();
    }

}
